package es.udc.emarketapp.http.controller.actions.products;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import es.udc.emarketapp.emarket.model.product.vo.ProductVO;
import es.udc.emarketapp.emarket.model.productFacade.ProductFacade;
import es.udc.emarketapp.http.controller.session.SessionManager;
import es.udc.emarketapp.http.view.actionForms.ProductForm;
import es.udc.fbellas.j2ee.util.exceptions.InternalErrorException;
import es.udc.fbellas.j2ee.util.struts.action.DefaultAction;
import org.apache.struts.upload.FormFile;

public class UpdateProductDetailsAction extends DefaultAction {

    public ActionForward doExecute(ActionMapping mapping,
            ActionForm form, HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException, InternalErrorException, InternalErrorException {

        ActionMessages errors = new ActionMessages();


        /* Get data. */
        ProductForm productForm = (ProductForm) form;

        Long idProd = productForm.getIdProd();
        Long idCat = productForm.getIdCat();
        String name = productForm.getName();
        String description = productForm.getDescription();
        double price = productForm.getPriceAsDouble();
        double weight = productForm.getWeightAsDouble();
        String country = productForm.getCountry();
        Long uds = productForm.getUdsAsLong();
        FormFile imageFile = productForm.getImage();
        byte[] image = imageFile.getFileData();

        byte[] imageIn = null;
        if (image.length > 0) {
            imageIn = image;
        }

        ProductFacade productFacade = new ProductFacade();

        ProductVO productVO = new ProductVO(idProd, SessionManager.getIdUser(request),
                idCat, name, description, country, uds, imageIn, price,
                weight, true);

        try {

            ProductVO insertedProductVO = productFacade.modifyProduct(productVO);
            request.setAttribute("product", insertedProductVO);

        } catch (InternalErrorException e) {
            errors.add("ProductIdentifier",
            new ActionMessage("ErrorMessages.product.notFound"));
            saveErrors(request, errors);
            System.out.println("Error al actualizar el producto " + e);
        }


        /* Return ActionForward. */
        if (errors.isEmpty()) {
            return mapping.findForward("productDetails");
        } else {
            saveErrors(request, errors);
            return new ActionForward(mapping.getInput());
        }
    }
}
